class Solution {
public:
    int bs(vector<int>& ends, int len, int k)
    {
        int l = 0, r = len - 1;
        int ans = -1;
        while(l <= r)
        {
            int mid = (l + r) >> 1;
            if(ends[mid] >= k)
            {
                ans = mid;
                r = mid - 1;
            }
            else
                l = mid + 1;
        }
        return ans;
    }

    int findLongestChain(vector<vector<int>>& pairs) {
        sort(pairs.begin(), pairs.end(), [](const auto& p1, const auto& p2){
            return p1[0] < p2[0];
        });

        int m = pairs.size();
        vector<int> ends(m, 0);

        int len = 0;
        for(auto& e : pairs)
        {
            int tmp = bs(ends, len, e[0]);
            if(tmp == -1)
                ends[len++] = e[1];
            else
            {
                if(e[1] < ends[tmp])
                    ends[tmp] = e[1];
            }
        }
        return len;
    }
};
